#include <iostream>
using namespace std;
#include <time.h>

// 截胡
void f1()
{
    try
    {
        int x, y;
        cin >> x >> y;
        auto mydiv = [&]()
        {if(y==0){throw string("除0错误");}return x/y; };
        cout << mydiv() << endl;
    }
    catch (string &e)
    {
        cout << __LINE__ << endl;
    }
}

// 异常安全问题
void f2()
{
    int *arr = new int[10];

    // 如果在这里发生了异常，那么就会跳出函数，这就会造成内存泄漏
    // 解决方法：捕获了异常后释放空间，然后再抛出异常

    try
    {
        int x, y;
        cin >> x >> y;
        auto mydiv = [&]()
        {
            if (y == 0)
            {
                throw string("除0错误");
            }
            return x / y;
        };
        cout << mydiv() << endl;
    }
    catch (...)
    {
        cout << "delete" << endl;
        delete[] arr;
        throw;
    }

    delete[] arr;
}

// 3:自定义异常体系：使用派生类来抛出异常，只有一个基类来捕获异常
class Execption
{
public:
    // 使用多态
    Execption(const int &code, const string &str) : _exit_code(code), _message(str)
    {
    }
    virtual string what() = 0; // 纯虚函数
protected:
    int _exit_code;  // 退出码
    string _message; // 退出信息
};

class Sqlerron : public Execption
{
public:
    Sqlerron(const int code, const string &str) : Execption(code, str)
    {
    }

    // 重写基类的虚函数
    virtual string what()
    {
        return "数据库错误" + _message;
    }
};
class IOerrno : public Execption
{
public:
    IOerrno(const int code, const string &str) : Execption(code, str)
    {
    }
    virtual string what()
    {
        return "IO错误" + _message;
    }
};
class Neterrno : public Execption
{
public:
    Neterrno(const int code, const string &str) : Execption(code, str)
    {
    }
    virtual string what()
    {
        return "网络错误" + _message;
    }
};

void servererrno()
{
    if (rand() % 3 == 0)
    {
        throw Sqlerron(1, "数据库启动失败");
    }
    if (rand() % 3 == 1)
    {
        throw IOerrno(2, "io流启动失败");
    }
    if (rand() % 2 == 0)
    {
        throw Sqlerron(3, "网络启动失败");
    }
}

int m2()
{

    for (int i = 0; i < 100; i++)
    {
        try
        {
            servererrno();
        }
        catch (Execption &e)
        { // 这里使用基类来捕获异常
            cout << e.what() << endl;
        }
        catch (...)
        {
            cout << "未知错误" << endl;
        }
    }
    // f1();
    // f2();//

    return 0;
}

#include <pthread.h>
#include <thread>
#include <mutex>
#include <condition_variable>
int main()
{
    int n = 100;
    thread t1([n]()
              {for(int i = 0;i<=n;i+=2){
        cout<<pthread_self() <<":"<< n<<endl;
    } }, n);

    thread t2([n]()
              {for(int i = 1;i<=n;i+=2){
        cout<<pthread_self()<<":"<<n<<endl;
    } }, n);

    t1.join();
    t2.join();

    return 0;
}